// address.js

const db = wx.cloud.database();
const addressCollection = db.collection('address');

Page({
  data: {
    address: {
      _id: '',
      name: '',
      phone: '',
      detail: '',
      userId: '',
    },
    addressList: [],
  },

  onLoad() {},

  onShow() {
    this.getAddressList();
  },

  // 获取地址列表
  getAddressList() {
    addressCollection.get({
      success: res => {
        this.setData({
          addressList: res.data
        });
        this.setDefaultAddress();
      },
      fail: err => {
        console.error('获取地址列表失败', err);
      }
    });
  },

  // 添加地址
  addAddress(address) {
    addressCollection.add({
      data: address,
      success: res => {
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        });
        this.getAddressList();
      },
      fail: err => {
        console.error('保存失败', err);
      }
    });
  },

  // 修改地址
  editAddress(address) {
    db.collection('address').doc(address._id).update({
      data: {
        name: address.name,
        phone: address.phone,
        detail: address.detail,
      },
      success: res => {
        wx.showToast({
          title: '修改成功',
          icon: 'success',
          duration: 2000
        });
        this.getAddressList();
      },
      fail: err => {
        console.error('修改失败', err);
      }
    });
  },

  // 删除地址
  deleteAddress(address) {
    wx.showModal({
      title: '提示',
      content: '确定要删除这个地址吗？',
      success: res => {
        if (res.confirm) {
          addressCollection.doc(address._id).remove({
            success: res => {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              });
              this.getAddressList();
            },
            fail: err => {
              console.error('删除失败', err);
            }
          });
        }
      }
    });
  },

  // 提交表单
  formSubmit(e) {
    const address = e.detail.value;
    const eid = this.data.address._id;
    if (address.name && address.phone && address.detail) {
      if (eid) {
        // 更新地址
        address._id = eid;
        this.editAddress(address);
      } else {
        // 添加地址
        this.addAddress(address);
      }
    } else{
      wx.showModal({
        title: '提示',
        content: '请填写完整资料',
        showCancel: false
      });
    }
  },

  // 设置默认地址
  setDefaultAddress() {
    const defaultAddress = this.data.addressList.find(item => item.checked);
    if (!defaultAddress && this.data.addressList.length > 0) {
      this.setData({
        ['addressList[0].checked']: true
      });
      this.updateCheckedAddress(this.data.addressList[0]);
    }
  },

  // 更新选中的地址
  updateCheckedAddress(address) {
    this.data.addressList.forEach(item => {
      if (item._id === address._id) {
        item.checked = true;
      } else {
        item.checked = false;
      }
    });
    this.setData({
      addressList: this.data.addressList
    });
  },

  // 选中地址
  onRadioChange(e) {
    const addressId = e.detail.value;
    const address = this.data.addressList.find(item => item._id === addressId);
    this.updateCheckedAddress(address);
    this.editAddress(address);
  },

  // 编辑地址
  edit(e) {
    const idx = e.currentTarget.dataset.idx; // 获取当前操作的地址在列表中的索引
    const address = this.data.addressList[idx]; // 获取当前操作的地址对象
    wx.navigateTo({
      // 跳转到 edit 页面，并将地址对象作为参数传递过去
      url: `/pages/edit/edit?_id=${address._id}&name=${address.name}&phone=${address.phone}&detail=${address.detail}`
    });
  },

  // 删除地址
  remove(e) {
    const idx = e.currentTarget.dataset.idx;
    const address = this.data.addressList[idx];
    this.deleteAddress(address);
  },


});